<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of image
 *
 * @author b4by
 */
class image extends MY_Controller {

	function __construct() {
		parent::__construct();
		$this->load->model('model_image');
	}

	public function index() {
		$this->data['module_name'] = lang('image_manage');
		$this->data['module_desc'] = lang('image_manage_desc');
		$this->data['module'] = 'image';
		$this->data['temp'] = 'admin/image/index';
		$this->load->view('admin/main', $this->data);
	}

	public function read() {

		$pagination = pagination_init($this->model_image->get_total(array('video' => 0)), request('p', 1));

		$images = $this->model_image->get_list(array(
			'where' => array('video' => 0),
			'limit' => array($pagination->from, $pagination->limit)
				));
		foreach ($images as &$image) {
			$image->thumb2 = image_url($image->thumb2);
			$image->link = url_create('site', 'photo', 'index', $image->id);
		}

		echo json_encode(array(
			'state' => 'success',
			'data' => $images,
			'pagination' => $pagination,
		));
	}

	public function suppend() {
		$this->load->helper('form');
		$this->load->library('form_validation');

		$this->form_validation->set_rules('id', 'id', 'required|callback__check_id');
		if ($this->validation_run()) {
			$this->model_image->update($this->input->post('id'), array(
				'suppend' => $this->input->post('suppend') == 0 ? 0 : 1,
			));
			echo json_encode(array(
				'state' => 'success',
				'id' => $this->input->post('id')
			));
		} else {
			echo json_encode(array(
				'state' => 'error',
				'title' => lang('error'),
				'message' => $this->data['error_message']
			));
		}
	}

	public function delete() {
		$this->load->helper('form');
		$this->load->library('form_validation');

		$this->form_validation->set_rules('id', 'id', 'required|callback__check_id');
		if ($this->validation_run()) {

			$image = $this->model_image->get_info($this->input->post('id'));
//			pr($image);die;
			if ($image->video != 1) {
				$this->deleteImage($image->path);
				$this->deleteImage($image->thumb);
				$this->deleteImage($image->thumb2);
			}
			$this->model_image->del($this->input->post('id'));
			echo json_encode(array(
				'state' => 'success',
				'id' => $this->input->post('id')
			));
		} else {
			echo json_encode(array(
				'state' => 'error',
				'title' => lang('error'),
				'message' => $this->data['error_message']
			));
		}
	}

	public function _check_id($id) {
		if ($this->model_image->get_total(array('id' => $id)) > 0)
			return TRUE;
		$this->form_validation->set_message(lang('image_not_exist'));
		return FALSE;
	}

}

?>
